package au.edu.unsw.editingtool.web.limited;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;

import org.xml.sax.SAXException;

import au.edu.unsw.editingtool.fedora.FedoraFactory;
import au.edu.unsw.editingtool.global.EditingToolException;
import au.edu.unsw.editingtool.global.EditingToolGlobalConstant;
import au.edu.unsw.editingtool.global.EditingToolPropertyReader;
import au.edu.unsw.editingtool.global.EditingToolUtil;

/**
 * Servlet implementation class ClaimRequest
 */
public class ClaimRequest extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String datastreamID = "";
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ClaimRequest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doService(request, response);
	}
	
	private FedoraFactory setupFedora(HttpServletRequest request, EditingToolPropertyReader reader) throws IOException {
		
		Hashtable<String, String> properties = EditingToolUtil.getProperties(reader, EditingToolPropertyReader.FEDORA);
		this.datastreamID = properties.get("datastream");
		
		return new FedoraFactory(properties.get("host") + ":" + properties.get("port") + properties.get("path"), 
												 properties.get("username"), properties.get("password"));
	}
	
	private Hashtable<String, String> grabFormData(String valetXML) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
		// plan is very simple, make all of them as textareas.
		// An example for the label, description_label -> Description Label:
		
		return EditingToolUtil.getNodeListViaPath("//Formdata", valetXML);
	}
	
	protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getAttribute(EditingToolGlobalConstant.claimRequested).equals(Boolean.TRUE)) {
			PrintWriter writer = response.getWriter();
			response.setContentType("text/html");
		    response.setCharacterEncoding("UTF-8");
		    writer.println("<h1>Notice:</h1>");
		    writer.println("Your request of claiming publication: " + 
		    							  request.getParameter(EditingToolGlobalConstant.requestPid) + 
		    							  " has not been processed yet, you'll received an email when it's done.");
		    response.flushBuffer();
		    writer.close();
		} else {
			// use fedora api to grab the result and display.
			String servletContext = getServletContext().getRealPath("") + EditingToolGlobalConstant.fileSeparator;
			String valetXML = "";
			
			EditingToolPropertyReader reader = new EditingToolPropertyReader();
			reader.setFile(servletContext + EditingToolGlobalConstant.configFilePath);
			
			FedoraFactory fedora = this.setupFedora(request, reader);  
			
			
			try {
				valetXML = EditingToolUtil.getValetXML(request.getSession(false).getId(), 
													   request.getParameter(EditingToolGlobalConstant.requestPid), this.datastreamID, fedora, reader);
				sendFormData(grabFormData(valetXML), request, response);
			} catch (EditingToolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TransformerConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TransformerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (XPathExpressionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	private void sendFormData(Hashtable<String, String> formData, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("/editPublication.jsp");
		request.setAttribute("pubTitle", "Claim Publication");
		request.setAttribute("pubMessage", "When you finished, click submit.");
		request.setAttribute("pubButton", EditingToolGlobalConstant.buttonTypeSubmit);
		request.setAttribute("pubReadonly", "readonly");
		request.setAttribute(EditingToolGlobalConstant.requestFormAction, "ClaimHandler");
		request.setAttribute(EditingToolGlobalConstant.requestCommandType, EditingToolGlobalConstant.commandClaim);
		request.setAttribute(EditingToolGlobalConstant.requestFormData, formData);
		dispatcher.forward(request, response);
	}

}
